package com.cskaoyan.market.service;

import com.cskaoyan.market.db.domain.*;
import com.cskaoyan.market.db.mapper.*;
import com.cskaoyan.market.vo.WxCartCheckoutVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class WxCartServiceImpl implements WxCartService{
    //商品界面下单id记录
    private static Integer fastAddCartId = 0;

    @Autowired
    SecurityManager securityManager;

    @Autowired
    MarketCartMapper marketCartMapper;

    @Autowired
    MarketAddressMapper marketAddressMapper;

    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;

    @Autowired
    MarketCouponMapper marketCouponMapper;

    @Autowired
    MarketSystemMapper marketSystemMapper;

    @Override
    @Transactional
    public int update(MarketCart marketCart) {
        marketCart.setUpdateTime(LocalDateTime.now());
        int i = marketCartMapper.updateByPrimaryKeySelective(marketCart);
        return i;
    }

    @Override
    @Transactional
    public List<MarketCart> delete(List<Integer> ids) {
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        //获取session
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();

        MarketUser user = (MarketUser) session.getAttribute("user");
        criteria.andUserIdEqualTo(user.getId());
        criteria.andProductIdIn(ids);
        int i = marketCartMapper.deleteByExample(marketCartExample);

        MarketCartExample marketCartExample1 = new MarketCartExample();
        MarketCartExample.Criteria criteria1 = marketCartExample1.createCriteria();
        criteria1.andUserIdEqualTo(user.getId());
        List<MarketCart> marketCartList = marketCartMapper.selectByExample(marketCartExample1);

        return marketCartList;

    }

    @Override
    public List<MarketCart> index() {
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser user = (MarketUser) session.getAttribute("user");
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andUserIdEqualTo(user.getId());
        List<MarketCart> marketCartList = marketCartMapper.selectByExample(marketCartExample);
        return marketCartList;
    }

    @Override
    public int goodsCount() {
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser user = (MarketUser) session.getAttribute("user");
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andUserIdEqualTo(user.getId());
        List<MarketCart> marketCartList = marketCartMapper.selectByExample(marketCartExample);
        int sum = 0;
        for (MarketCart marketCart : marketCartList) {
            sum += marketCart.getNumber();
        }
        return sum;
    }

    @Override
    public double goodsAmount() {
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser user = (MarketUser) session.getAttribute("user");
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andUserIdEqualTo(user.getId());
        List<MarketCart> marketCartList = marketCartMapper.selectByExample(marketCartExample);
        double totalPrice = 0;
        for (MarketCart marketCart : marketCartList) {
            Short number = marketCart.getNumber();
            double price = marketCart.getPrice().doubleValue();
            totalPrice += number*price;
        }
        return totalPrice;
    }

    @Override
    public double checkedGoodsAmount() {
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser user = (MarketUser) session.getAttribute("user");
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andUserIdEqualTo(user.getId());
        criteria.andCheckedEqualTo(true);
        List<MarketCart> marketCartList = marketCartMapper.selectByExample(marketCartExample);
        double totalPrice = 0;
        for (MarketCart marketCart : marketCartList) {
            Short number = marketCart.getNumber();
            double price = marketCart.getPrice().doubleValue();
            totalPrice += number*price;
        }
        return totalPrice;
    }

    @Override
    public int checkedGoodsCount() {
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser user = (MarketUser) session.getAttribute("user");
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andUserIdEqualTo(user.getId());
        criteria.andCheckedEqualTo(true);
        List<MarketCart> marketCartList = marketCartMapper.selectByExample(marketCartExample);
        int sum = 0;
        for (MarketCart marketCart : marketCartList) {
            sum += marketCart.getNumber();
        }
        return sum;
    }

    @Override
    @Transactional
    public int add(MarketCart marketCart) {
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser user = (MarketUser) session.getAttribute("user");
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andUserIdEqualTo(user.getId());
        criteria.andGoodsIdEqualTo(marketCart.getGoodsId());
        criteria.andProductIdEqualTo(marketCart.getProductId());
        MarketCart marketCart2 = marketCartMapper.selectOneByExample(marketCartExample);
        int i=0;
        if(marketCart2!=null){
            Short number1 = marketCart.getNumber();
            Short number2 = marketCart2.getNumber();
            marketCart2.setNumber((short) (number1+number2));
            marketCart2.setUpdateTime(LocalDateTime.now());
            i = marketCartMapper.updateByExampleSelective(marketCart2, marketCartExample);
        }else {
            // 自建sql
            MarketCart marketCart1 = marketCartMapper.wjhSelect(marketCart.getProductId());
            marketCart1.setUpdateTime(LocalDateTime.now());
            marketCart1.setAddTime(LocalDateTime.now());
            marketCart1.setChecked(true);
            marketCart1.setNumber(marketCart.getNumber());
            marketCart1.setUserId(user.getId());
            i = marketCartMapper.insert(marketCart1);
        }
        return i;
    }

    @Override
    @Transactional
    public List<MarketCart> checked(int isChecked, List<Integer> productIds) {
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser user = (MarketUser) session.getAttribute("user");
        boolean flag=false;
        if(isChecked==1){
            flag=true;
        }
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andUserIdEqualTo(user.getId());
        criteria.andProductIdIn(productIds);
        MarketCart marketCart = new MarketCart();
        marketCart.setChecked(flag);
        marketCartMapper.updateByExampleSelective(marketCart,marketCartExample);

        MarketCartExample marketCartExample1 = new MarketCartExample();
        MarketCartExample.Criteria criteria1 = marketCartExample1.createCriteria();
        criteria1.andUserIdEqualTo(user.getId());
        List<MarketCart> marketCartList = marketCartMapper.selectByExample(marketCartExample1);
        return marketCartList;
    }

    @Override
    @Transactional
    public int fastAdd(MarketCart marketCart) {
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser user = (MarketUser) session.getAttribute("user");
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andUserIdEqualTo(user.getId());
        criteria.andGoodsIdEqualTo(marketCart.getGoodsId());
        criteria.andProductIdEqualTo(marketCart.getProductId());
        MarketCart cart = marketCartMapper.selectOneByExample(marketCartExample);

        if(cart!=null){
            marketCart.setUpdateTime(LocalDateTime.now());
            marketCartMapper.updateByExampleSelective(marketCart, marketCartExample);
            //这里返回的是cart表中的id
            fastAddCartId=cart.getId();
            return cart.getId();
        }else {
            // 自建sql
            MarketCart marketCart1 = marketCartMapper.wjhSelect(marketCart.getProductId());
            marketCart1.setUpdateTime(LocalDateTime.now());
            marketCart1.setAddTime(LocalDateTime.now());
            marketCart1.setChecked(true);
            marketCart1.setNumber(marketCart.getNumber());
            marketCart1.setUserId(user.getId());
            marketCartMapper.insert(marketCart1);
            MarketCart marketCart2 = marketCartMapper.selectOneByExample(marketCartExample);
            fastAddCartId = marketCart2.getId();
            return marketCart2.getId();
        }

    }

    @Override
    public WxCartCheckoutVo checkout(WxCartCheckoutVo vo) {
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser user = (MarketUser) session.getAttribute("user");
        double goodsTotalPrice = 0;
        //满足免运费
        MarketSystem marketExpressFreightMin = marketSystemMapper.selectByPrimaryKey(6);
        double freightMin = Double.parseDouble(marketExpressFreightMin.getKeyValue());
        //运费
        MarketSystem marketExpressFreightValue = marketSystemMapper.selectByPrimaryKey(8);
        double freightValue = Double.parseDouble(marketExpressFreightValue.getKeyValue());
        //整合商品优惠前总价和需付款商品列表
        if(vo.getCartId()==0){
            //通过购物车页面下单
            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
            criteria.andCheckedEqualTo(true);
            criteria.andUserIdEqualTo(user.getId());
            List<MarketCart> checkGoodsList = marketCartMapper.selectByExample(marketCartExample);
            vo.setCheckedGoodsList(checkGoodsList);
            vo.setGoodsTotalPrice(checkedGoodsAmount());
            goodsTotalPrice = checkedGoodsAmount();
        }else {
            //直接通过商品页面下单
            List<MarketCart> marketCarts = new ArrayList<>();
            MarketCart marketCart = marketCartMapper.selectByPrimaryKey(fastAddCartId);
            marketCarts.add(marketCart);
            int number = marketCart.getNumber().intValue();
            double price = marketCart.getPrice().doubleValue();
            goodsTotalPrice = number * price;
            vo.setGoodsTotalPrice(goodsTotalPrice);
            vo.setCheckedGoodsList(marketCarts);
        }
        if(vo.getAddressId()==0){
            //整合用户地址
            MarketAddressExample marketAddressExample = new MarketAddressExample();
            MarketAddressExample.Criteria criteria = marketAddressExample.createCriteria();
            criteria.andIsDefaultEqualTo(true);
            criteria.andUserIdEqualTo(user.getId());
            MarketAddress marketAddress = marketAddressMapper.selectOneByExample(marketAddressExample);
            vo.setCheckedAddress(marketAddress);
        }else {
            MarketAddress marketAddress = marketAddressMapper.selectByPrimaryKey(vo.getAddressId());
            vo.setCheckedAddress(marketAddress);
        }
        //判断运费
        if(goodsTotalPrice>=freightMin){
            freightValue=0;
        }

        if(vo.getCouponId()==-1||vo.getCouponId()==0){
            int couponNums = 0;
            MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
            MarketCouponUserExample.Criteria criteria = marketCouponUserExample.createCriteria();
            criteria.andUserIdEqualTo(user.getId());
            criteria.andStatusEqualTo((short) 0);
            List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
            Integer flag = null;
            Integer userCouponId = 0;
            for (MarketCouponUser marketCouponUser : marketCouponUsers) {
                MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(marketCouponUser.getCouponId());
                if(goodsTotalPrice>marketCoupon.getMin().doubleValue()){
                    flag = marketCoupon.getId();
                    userCouponId = marketCouponUser.getId();//设置userCouponId
                    couponNums++;
                }
            }
            vo.setAvailableCouponLength(couponNums);//设置可用优惠劵

            if(couponNums>0){
                MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(flag);
                double disCount = marketCoupon.getDiscount().doubleValue();
                if(vo.getCouponId()==-1){
                    vo.setCouponId(-1);
                    vo.setUserCouponId(-1);
                    vo.setCouponPrice(0);
                    vo.setActualPrice(goodsTotalPrice+freightValue);
                    vo.setOrderTotalPrice(goodsTotalPrice+freightValue);
                }
                if(vo.getCouponId()==0){
                    vo.setCouponId(marketCoupon.getId());
                    vo.setUserCouponId(userCouponId);//设置userCouponId
                    vo.setCouponPrice(disCount);
                    vo.setActualPrice(goodsTotalPrice-disCount+freightValue);
                    vo.setOrderTotalPrice(goodsTotalPrice-disCount+freightValue);
                }

            }else {
//                vo.setAvailableCouponLength(0);
//                vo.setCouponId(0);
                vo.setCouponPrice(0);
                vo.setActualPrice(goodsTotalPrice+freightValue);
                vo.setOrderTotalPrice(goodsTotalPrice+freightValue);
            }

        }
        if(vo.getCouponId()>0){
            int couponNums = 0;
            MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
            MarketCouponUserExample.Criteria criteria = marketCouponUserExample.createCriteria();
            criteria.andUserIdEqualTo(user.getId());
            criteria.andStatusEqualTo((short) 0);
            List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
            for (MarketCouponUser marketCouponUser : marketCouponUsers) {
                MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(marketCouponUser.getCouponId());
                if(goodsTotalPrice>marketCoupon.getMin().doubleValue()){
                    couponNums++;
                }
            }
            Integer couponId = vo.getCouponId();
            MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(couponId);
            double disCount = marketCoupon.getDiscount().doubleValue();
            vo.setCouponPrice(disCount);
            vo.setAvailableCouponLength(couponNums);//设置可用优惠劵
            vo.setActualPrice(goodsTotalPrice-disCount+freightValue);
            vo.setOrderTotalPrice(goodsTotalPrice-disCount+freightValue);

        }

        //团购和运费
        vo.setFreightPrice(freightValue);
        vo.setGrouponPrice(0);
        vo.setGrouponRulesId(0);

        return vo;

    }

}
